package com.itstorm.pomeloweather.ui;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itstorm.pomeloweather.R;
import com.itstorm.pomeloweather.entity.DataStatus;
import com.itstorm.pomeloweather.entity.ListViewHolder;
import com.itstorm.pomeloweather.entity.PagerStatus;
import com.itstorm.pomeloweather.entity.WeatherData;
import com.itstorm.pomeloweather.entity.WeatherIndex;
import com.itstorm.pomeloweather.entity.WeatherResults;
import com.itstorm.pomeloweather.util.Blur;
import com.itstorm.pomeloweather.util.BroadcastCode;
import com.itstorm.pomeloweather.util.ImageUtils;
import com.itstorm.pomeloweather.util.ScrollableImageView;
import com.itstorm.pomoloweather.dao.WeatherDao;

public class WeatherPageFragment extends Fragment {

	private static final String IMG_PREF = "blurred.";
	private static final String IMG_SUFF = ".png";
	private static final int HANDLER_NETWORK_FLAG = 0;
	private static final int HANDLER_CLEARANMI_FLAG = 9;
	private static final int HANDLER_WIND_FLAG = 8;
	private static final int TOP_HEIGHT = 700;

	/** 时间 */
	private TextView tvDate;
	/** 城市 */
	private TextView tvCity;
	/** 设置按钮 */
	private ImageButton btnRefresh;
	private ImageButton btnMenu;
	private ImageView imgBg;
	private ImageView imgBgFront;
	private ListView list;
	private View headerView;
	private ScrollableImageView mBlurredImageHeader;
	private Animation leftWindAnim;
	private Animation rightWindAnim;
	private Animation refreshAnim;
	private ArrayList<WeatherData> weatherDatas;
	private ArrayList<WeatherIndex> weatherIndexs;
	private DataStatus dataStatus;
	private ListViewHolder holder;
	private ExecuteNetWorkThread ent;
	private String json = "";
	private float alpha;
	private WeatherResults weatherResults;
	private int screenWidth;
	private int bgResource;
	private int marginTop;
	private Display mDisplay;
	private String mAreas;
	private BroadcastReceiver mReceiver;
	private SharedPreferences weatherList;
	private SharedPreferences.Editor editor;
	private boolean blurred;
	private boolean showToast;
	private Context context;
	private View view;
	private PagerStatus pagerStatus;

	public WeatherPageFragment(Context context, int mIndex,
			PagerStatus mPagerStatus) {
		super();
		this.pagerStatus = mPagerStatus;
		this.mAreas = pagerStatus.getAreasName();
		this.context = context;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		showToast = false;
		view = inflater.inflate(R.layout.activity_weather_page, container,
				false);
		weatherList = context.getSharedPreferences("WeatherList", 0);
		editor = weatherList.edit();
		blurred = weatherList.getBoolean("blurred", true);
		setupView();
		getUserAreasList();
		return view;
	}

	@Override
	public void onViewStateRestored(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewStateRestored(savedInstanceState);
		weatherList = context.getSharedPreferences("WeatherList", 0);
		blurred = weatherList.getBoolean("blurred", false);
		getUserAreasList();
	}

	private void getUserAreasList() {
		// TODO Auto-generated method stub
		json = pagerStatus.getJson();
		if (json != null && !json.equals("")) {
			dataStatus = WeatherDao.getDataStatus(json);
			Message message = handler.obtainMessage();
			message.what = HANDLER_NETWORK_FLAG;
			message.arg1 = -1;
			handler.sendMessage(message);

			new Timer().schedule(new TimerTask() {
				public void run() {
					// execute the task
					Message message = handler.obtainMessage();
					message.what = 7;
					handler.sendMessage(message);
				}
			}, 5000);
		} else {
			new Timer().schedule(new TimerTask() {
				public void run() {
					// execute the task
					Message message = handler.obtainMessage();
					message.what = 7;
					handler.sendMessage(message);
				}
			}, 1000);
		}
	}

	private void update() {
		if (holder != null) {
			if (dataStatus != null) {
				if (dataStatus.getResultes() != null) {
					weatherResults = (WeatherResults) dataStatus.getResultes()
							.get(0);
					Log.d("JSON", "---------------Resultes---------------\n"
							+ weatherResults.toString());
					if (weatherResults != null) {
						weatherIndexs = weatherResults.getIndexs();
						Log.d("JSON", "---------------Indexs---------------\n"
								+ weatherIndexs.toString());
						weatherDatas = weatherResults.getData();
						Log.d("JSON", "---------------Datas---------------\n"
								+ weatherDatas.toString());

						// 城市
						String city = weatherResults.getCurrentCity();
						tvCity.setText(city);

						// pm2.5
						String pm25 = weatherResults.getPm25();
						Log.d("JSON", "---------------pm25---------------\n"
								+ pm25.toString());
						holder.tvPm25.setText("PM2.5: " + pm25);
					}

					if (weatherDatas != null) {
						holder.g3dAdapter.changeList(weatherDatas);
						holder.g3dAdapter.notifyDataSetChanged();
						WeatherData weatherData = weatherDatas.get(0);
						String wind = weatherData.getWind().toString();

						// 日期
						String date = weatherDatas.get(0).getDate();

						if (date.length() != 0) {
							if (date.contains("(")) {
								date = (String) date.substring(0,
										date.indexOf("("));
							}
							tvDate.setText(date);
						} else {
							tvDate.setText("N/A");
						}

						// 风速

						holder.tvWind.setText(wind);
						if (wind.contains("1")) {
							leftWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_1);
							rightWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_1);
						} else if (wind.contains("2")) {
							leftWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_2);
							rightWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_2);
						} else if (wind.contains("4") | wind.contains("3")) {
							leftWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_3);
							rightWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_3);
						} else if (wind.contains("6") | wind.contains("5")) {
							leftWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_4);
							rightWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_4);
						} else if (wind.contains("8") | wind.contains("7")) {
							leftWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_5);
							rightWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_5);
						} else {
							leftWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_0);
							rightWindAnim = AnimationUtils.loadAnimation(
									context, R.anim.rotate_wind_0);
						}

						rotateView();

						// 当前温度
						String current_temp = weatherDatas.get(0).getDate();
						if (current_temp.length() != 0) {
							if (current_temp.contains("(")) {
								current_temp = current_temp.substring(
										current_temp.indexOf("实时：") + 3,
										current_temp.length() - 2)
										+ "°";
							} else {
								current_temp = weatherDatas.get(0)
										.getTemperature().trim();
								if (current_temp.contains("~")) {
									current_temp = (String) current_temp
											.substring(
													current_temp.indexOf("~") + 1,
													current_temp.length() - 1)
											+ "°";
								} else {
									current_temp = (String) current_temp
											.subSequence(0,
													current_temp.length() - 1)
											+ "°";
								}
							}
						} else {
							current_temp = "N/A";
						}
						holder.tvCurrentTemp.setText(current_temp);

						// 温度区间
						String temp = weatherDatas.get(0).getTemperature();
						if (temp.length() != 0) {
							temp = "温度区间: " + temp;
						} else {
							temp = "温度区间: " + "N/A";
						}

						holder.tvTemp.setText(temp);
						holder.tvTempInfo.setText(temp);

						// 天气信息(图片+文字)
						SimpleDateFormat sdf = new SimpleDateFormat("HH");
						int mDate = Integer.parseInt(sdf
								.format(new java.util.Date()));
						Log.d("JSON", "---------------Time---------------\n"
								+ mDate + "");
						String weather = weatherDatas.get(0).getWeather();
						if (weather.length() != 0) {
							if (weather.contains("晴")) {
								holder.imgWeather
										.setImageResource(R.drawable.qing);
								holder.imgWeatherInfo
										.setImageResource(R.drawable.qing);
								if (mDate <= 18 && mDate >= 5) {
									bgResource = R.drawable.image_qing_d;
								} else {
									bgResource = R.drawable.image_qing_n;
								}
							} else if (weather.contains("风")) {
								holder.imgWeather
										.setImageResource(R.drawable.feng);
								holder.imgWeatherInfo
										.setImageResource(R.drawable.feng);
							} else if (weather.contains("霾")
									| weather.contains("雾")) {
								holder.imgWeather
										.setImageResource(R.drawable.mai);
								holder.imgWeatherInfo
										.setImageResource(R.drawable.mai);
								if (mDate <= 18 && mDate >= 5) {
									bgResource = R.drawable.image_mai_d;
								} else {
									bgResource = R.drawable.image_mai_n;
								}
							} else if (weather.contains("雪")) {
								holder.imgWeather
										.setImageResource(R.drawable.xue);
								holder.imgWeatherInfo
										.setImageResource(R.drawable.xue);
								if (mDate <= 18 && mDate >= 5) {
									bgResource = R.drawable.image_xue_d;
								} else {
									bgResource = R.drawable.image_xue_n;
								}
							} else if (weather.contains("阴")) {
								holder.imgWeather
										.setImageResource(R.drawable.yin);
								holder.imgWeatherInfo
										.setImageResource(R.drawable.yin);
								if (mDate <= 18 && mDate >= 5) {
									bgResource = R.drawable.image_yin_d;
								} else {
									bgResource = R.drawable.image_yin_n;
								}
							} else if (weather.contains("云")) {
								holder.imgWeather
										.setImageResource(R.drawable.yun);
								holder.imgWeatherInfo
										.setImageResource(R.drawable.yun);
								if (mDate <= 18 && mDate >= 5) {
									bgResource = R.drawable.image_yun_d;
								} else {
									bgResource = R.drawable.image_yun_n;
								}
							} else if (weather.contains("雨")) {
								if (weather.contains("大雨")
										| weather.contains("暴雨")) {
									holder.imgWeather
											.setImageResource(R.drawable.dayu);
									holder.imgWeatherInfo
											.setImageResource(R.drawable.dayu);
								} else if (weather.contains("中雨")
										| weather.contains("阵雨")) {
									holder.imgWeather
											.setImageResource(R.drawable.zhongyu);
									holder.imgWeatherInfo
											.setImageResource(R.drawable.zhongyu);
								} else {
									holder.imgWeather
											.setImageResource(R.drawable.xiaoyu);
									holder.imgWeatherInfo
											.setImageResource(R.drawable.xiaoyu);
								}
							}
						} else {
							weather = "N/A";
							holder.imgWeather
									.setImageResource(R.drawable.weather_default);
							holder.imgWeatherInfo
									.setImageResource(R.drawable.weather_default);
							bgResource = R.drawable.image_default;
						}
						holder.tvWeather.setText(weather);
						holder.tvWeatherInfo.setText(weather);
					}

					if (weatherIndexs != null) {
						// 指数
						for (int i = 0; i < weatherIndexs.size(); i++) {
							if (weatherIndexs.get(i).getTitle().equals("穿衣")) {
								holder.tvCy.setText("穿衣: "
										+ weatherIndexs.get(i).getZs());
								holder.tvCyzs.setText("穿衣指数: \n"
										+ weatherIndexs.get(i).getDes());
							} else if (weatherIndexs.get(i).getTitle()
									.equals("洗车")) {
								holder.tvXc.setText("洗车: "
										+ weatherIndexs.get(i).getZs());
								holder.tvXczs.setText("洗车指数: \n"
										+ weatherIndexs.get(i).getDes());
							} else if (weatherIndexs.get(i).getTitle()
									.equals("旅游")) {
								holder.tvLy.setText("旅游: "
										+ weatherIndexs.get(i).getZs());
								holder.tvLyzs.setText("旅游指数: \n"
										+ weatherIndexs.get(i).getDes());
							} else if (weatherIndexs.get(i).getTitle()
									.equals("感冒")) {
								holder.tvGm.setText("感冒: "
										+ weatherIndexs.get(i).getZs());
								holder.tvGmzs.setText("感冒指数: \n"
										+ weatherIndexs.get(i).getDes());
							} else if (weatherIndexs.get(i).getTitle()
									.equals("运动")) {
								holder.tvYd.setText("运动: "
										+ weatherIndexs.get(i).getZs());
								holder.tvYdzs.setText("运动指数: \n"
										+ weatherIndexs.get(i).getDes());
							} else if (weatherIndexs.get(i).getTitle()
									.equals("紫外线强度")) {
								holder.tvZwx.setText("紫外线强度: "
										+ weatherIndexs.get(i).getZs());
								holder.tvZwxzs.setText("紫外线强度指数: \n"
										+ weatherIndexs.get(i).getDes());
							} else {
								holder.tvCy.setText("穿衣: N/A");
								holder.tvCyzs.setText("穿衣指数: \nN/A");
								holder.tvXc.setText("洗车: N/A");
								holder.tvXczs.setText("洗车指数: \nN/A");
								holder.tvLy.setText("旅游: N/A");
								holder.tvLyzs.setText("旅游指数: \nN/A");
								holder.tvGm.setText("感冒: N/A");
								holder.tvGmzs.setText("感冒指数: \nN/A");
								holder.tvYd.setText("运动: N/A");
								holder.tvYdzs.setText("运动指数: \nN/A");
								holder.tvZwx.setText("紫外线强度: N/A");
								holder.tvZwxzs.setText("紫外线强度指数: \nN/A");
							}
						}
						// 设置背景图
						setImgBg();
					}
				}
			}
		}
	}

	private void setupView() {
		bgResource = R.drawable.image_default;
		screenWidth = ImageUtils.getScreenWidth(this.getActivity());
		holder = pagerStatus.getViewHolder();
		setViews();
		MainListAdapter mainListAdapter = new MainListAdapter();

		leftWindAnim = AnimationUtils
				.loadAnimation(context, R.anim.rotate_wind);
		rightWindAnim = AnimationUtils.loadAnimation(context,
				R.anim.rotate_wind);
		refreshAnim = AnimationUtils.loadAnimation(context,
				R.anim.rotate_wind_4);
		tvDate = (TextView) view.findViewById(R.id.tv_date);
		tvCity = (TextView) view.findViewById(R.id.tv_city);
		imgBg = (ImageView) view.findViewById(R.id.img_bg);
		imgBgFront = (ImageView) view.findViewById(R.id.img_bg_front);
		imgBgFront.setAlpha(0f);
		btnRefresh = (ImageButton) view.findViewById(R.id.btn_refresh);
		btnMenu = (ImageButton) view.findViewById(R.id.btn_menu);
		mBlurredImageHeader = (ScrollableImageView) view
				.findViewById(R.id.blurred_image_header);
		mBlurredImageHeader.setScreenWidth(screenWidth);

		list = (ListView) view.findViewById(R.id.list);
		headerView = new View(context);
		headerView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				TOP_HEIGHT));
		mDisplay = this.getActivity().getWindowManager().getDefaultDisplay();
		if (mDisplay.getHeight() == 1920) {
			marginTop = 0;
		} else if (mDisplay.getHeight() == 1280) {
			marginTop = 20 * 15;
		} else if (mDisplay.getHeight() == 854) {
			marginTop = 16 * 15;
		} else if (mDisplay.getHeight() == 800) {
			marginTop = 20 * 15;
		} else {
			marginTop = 20 * 15;
		}

		list.setPadding(0, -marginTop, 0, 0);
		list.addHeaderView(headerView);
		list.setAdapter(mainListAdapter);

		list.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				// Calculate the ratio between the scroll amount and the list
				// header weight to determinate the top picture alpha
				alpha = (float) -headerView.getTop() / (float) TOP_HEIGHT;
				if (alpha > 1) {
					alpha = 1;
				}
				if (blurred) {
					imgBgFront.setAlpha(alpha);
				} else {
					imgBgFront.setAlpha(0.5f);
				}
				imgBgFront.setTop(headerView.getTop() / 4);
				imgBg.setTop(headerView.getTop() / 4);
			}
		});

		btnRefresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showToast = true;
				btnRefresh.setClickable(false);
				LinearInterpolator lin = new LinearInterpolator();
				refreshAnim.setInterpolator(lin);
				btnRefresh.startAnimation(refreshAnim);
				ent = new ExecuteNetWorkThread();
				ent.start();
			}
		});

		btnMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				BaseActivity.slidingMenu.showMenu();
			}
		});

		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				if (intent.getAction().equals(BroadcastCode.changeBlur)) {
					weatherList = context
							.getSharedPreferences("WeatherList", 0);
					blurred = weatherList.getBoolean("blurred", false);
				}
			}
		};
		IntentFilter mIntentFilter = new IntentFilter(BroadcastCode.changeBlur);
		context.registerReceiver(mReceiver, mIntentFilter);
	}

	private class ExecuteNetWorkThread extends Thread {
		@Override
		public void run() {
			Message message = handler.obtainMessage();
			message.what = HANDLER_NETWORK_FLAG;
			message.arg1 = 1;
			json = null;
			// Http客户端
			HttpClient client;
			// get请求
			HttpGet get;
			// 服务器返回的相应
			HttpResponse response;
			// 响应的实体
			HttpEntity entity;
			// 访问的路径
			String uri = "http://api.map.baidu.com/telematics/v3/weather?location="
					+ mAreas
					+ "&output=json&ak="
					+ "B2ccecd37638222da1e21c0cafc07d41";
			try {
				client = new DefaultHttpClient();
				get = new HttpGet(uri);
				response = client.execute(get);
				entity = response.getEntity();
				json = EntityUtils.toString(entity);
				if (json != null) {

					editor.putString(mAreas, json.toString().trim());
					editor.commit();

					dataStatus = WeatherDao.getDataStatus(json);
					message.arg1 = 0;
				} else {
					message.arg1 = 1;
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			handler.sendMessage(message);
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_NETWORK_FLAG:
				if (msg.arg1 == 1) {
					btnRefresh.clearAnimation();
					ImageUtils.showToast(context, "网络服务不可用!", 2000,
							mDisplay.getWidth());
					btnRefresh.setClickable(true);
					showToast = false;
				} else if (msg.arg1 == 0) {
					btnRefresh.clearAnimation();
					if (showToast) {
						ImageUtils.showToast(context, "天气数据已更新", 2000,
								mDisplay.getWidth());
					}
					update();
					btnRefresh.setClickable(true);
					showToast = false;
				} else if (msg.arg1 == -1) {
					update();
					btnRefresh.setClickable(false);
					new Timer().schedule(new TimerTask() {
						public void run() {
							// execute the task
							Message message = handler.obtainMessage();
							message.what = 7;
							handler.sendMessage(message);
						}
					}, 5000);
					showToast = false;
				}
				break;
			case 7:
				btnRefresh.setClickable(false);
				ent = new ExecuteNetWorkThread();
				ent.start();
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void rotateView() {
		LinearInterpolator lin = new LinearInterpolator();
		leftWindAnim.setInterpolator(lin);
		rightWindAnim.setInterpolator(lin);
		if (leftWindAnim != null & rightWindAnim != null) {
			holder.imgWindFrontL.startAnimation(leftWindAnim);
			holder.imgWindFrontR.startAnimation(rightWindAnim);
		}
	}

	public void positionShow(int position) {
		if (holder != null) {
			switch (position) {
			case 0:
				holder.positionLeft
						.setBackgroundResource(R.drawable.shape_corner_position_bg_s);
				holder.positionMiddle
						.setBackgroundResource(R.drawable.shape_corner_position_bg_n);
				holder.positionRight
						.setBackgroundResource(R.drawable.shape_corner_position_bg_n);
				break;
			case 1:
				holder.positionLeft
						.setBackgroundResource(R.drawable.shape_corner_position_bg_n);
				holder.positionMiddle
						.setBackgroundResource(R.drawable.shape_corner_position_bg_s);
				holder.positionRight
						.setBackgroundResource(R.drawable.shape_corner_position_bg_n);
				break;
			case 2:
				holder.positionLeft
						.setBackgroundResource(R.drawable.shape_corner_position_bg_n);
				holder.positionMiddle
						.setBackgroundResource(R.drawable.shape_corner_position_bg_n);
				holder.positionRight
						.setBackgroundResource(R.drawable.shape_corner_position_bg_s);
				break;
			default:
				break;
			}
		}
	}

	public class MainListAdapter extends BaseAdapter {

		public MainListAdapter() {
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return 1;
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			// View rowView = ViewMap.getRowViews().get(index);
			View mConvertView = pagerStatus.getConvertView();
			if (mConvertView == null) {
				setViews();
			}
			return mConvertView;
		}
	}

	private void updateView(final int screenWidth) {
		Bitmap bmpBlurred = BitmapFactory.decodeFile(context.getFilesDir()
				+ IMG_PREF + bgResource + IMG_SUFF);
		if (bmpBlurred != null) {
			bmpBlurred = Bitmap
					.createScaledBitmap(
							bmpBlurred,
							screenWidth,
							(int) (bmpBlurred.getHeight()
									* ((float) screenWidth) / (float) bmpBlurred
									.getWidth()), false);
			imgBg.setImageResource(bgResource);
			imgBgFront.setImageBitmap(bmpBlurred);
		}
	}

	public void setImgBg() {
		final File blurredImage = new File(context.getFilesDir() + IMG_PREF
				+ bgResource + IMG_SUFF);
		if (!blurredImage.exists()) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					// No image found => let's generate it!
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 2;
					Bitmap image = BitmapFactory.decodeResource(getResources(),
							bgResource, options);
					Bitmap newImg = Blur.fastblur(context, image, 12);
					ImageUtils.storeImage(newImg, blurredImage);
					WeatherPageFragment.this.getActivity().runOnUiThread(
							new Runnable() {
								@Override
								public void run() {
									updateView(screenWidth);
								}
							});
				}
			}).start();
		} else {
			// The image has been found. Let's update the view
			updateView(screenWidth);
		}
	}

	public void setViews() {
		View mConvertView = pagerStatus.getConvertView();
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mConvertView = (LinearLayout) inflater
				.inflate(R.layout.list_item, null);
		pagerStatus.setConvertView(mConvertView);
		holder.setG3d((Gallery) mConvertView.findViewById(R.id.gallery_3days));
		holder.setTvCurrentTemp((TextView) mConvertView
				.findViewById(R.id.tv_current_temp));
		holder.setTvTemp((TextView) mConvertView.findViewById(R.id.tv_temp));
		holder.setTvTempInfo((TextView) mConvertView
				.findViewById(R.id.tv_temp_info));
		holder.setTvWeather((TextView) mConvertView
				.findViewById(R.id.tv_weather));
		holder.setTvWeatherInfo((TextView) mConvertView
				.findViewById(R.id.tv_weather_info));
		holder.setTvWind((TextView) mConvertView.findViewById(R.id.tv_wind));
		holder.setTvPm25((TextView) mConvertView.findViewById(R.id.tv_pm2_5));
		holder.setTvCy((TextView) mConvertView.findViewById(R.id.tv_cy));
		holder.setTvCyzs((TextView) mConvertView.findViewById(R.id.tv_cyzs));
		holder.setTvXc((TextView) mConvertView.findViewById(R.id.tv_xc));
		holder.setTvXczs((TextView) mConvertView.findViewById(R.id.tv_xczs));
		holder.setTvLy((TextView) mConvertView.findViewById(R.id.tv_ly));
		holder.setTvLyzs((TextView) mConvertView.findViewById(R.id.tv_lyzs));
		holder.setTvGm((TextView) mConvertView.findViewById(R.id.tv_gm));
		holder.setTvGmzs((TextView) mConvertView.findViewById(R.id.tv_gmzs));
		holder.setTvYd((TextView) mConvertView.findViewById(R.id.tv_yd));
		holder.setTvYdzs((TextView) mConvertView.findViewById(R.id.tv_ydzs));
		holder.setTvZwx((TextView) mConvertView.findViewById(R.id.tv_zwx));
		holder.setTvZwxzs((TextView) mConvertView.findViewById(R.id.tv_zwxzs));
		holder.setPositionLeft((LinearLayout) mConvertView
				.findViewById(R.id.position_l));
		holder.setPositionMiddle((LinearLayout) mConvertView
				.findViewById(R.id.position_m));
		holder.setPositionRight((LinearLayout) mConvertView
				.findViewById(R.id.position_r));
		holder.setImgWeather((ImageView) mConvertView
				.findViewById(R.id.img_weather));
		holder.setImgWeatherInfo((ImageView) mConvertView
				.findViewById(R.id.img_weather_info));
		holder.setImgWindBgL((ImageView) mConvertView
				.findViewById(R.id.img_wind_bg_l));
		holder.setImgWindFrontL((ImageView) mConvertView
				.findViewById(R.id.img_wind_front_l));
		holder.setImgWindBgR((ImageView) mConvertView
				.findViewById(R.id.img_wind_bg_r));
		holder.setImgWindFrontR((ImageView) mConvertView
				.findViewById(R.id.img_wind_front_r));
		holder.setRlInfo((RelativeLayout) mConvertView
				.findViewById(R.id.rl_info));
		holder.setG3dAdapter(new Gallery3DaysAdapter(context, weatherDatas));
		holder.g3d.setAdapter(holder.g3dAdapter);

		holder.g3d.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				positionShow(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		context.unregisterReceiver(mReceiver);
	}
}
